<template>
	<div class="table-header">
		<p>视频资料列表</p>
		<el-button type="primary" :loading="isLoading" @click="clickUpload">
			上传文件
		</el-button>
	</div>
	<el-divider style="margin-bottom: 24px; margin-top: 0px"></el-divider>
	<upload
		accept=".mp4"
		:show="showBox"
		mediatype="VIDEO"
		title="上传音频文件"
		@close="closeUpload"
		:setBoxShow="setBoxShow"
		@changeFiles="changeFiles"
		@complete="completeUpload"
		:setBtnLoading="setBtnLoading"
	></upload>

	<list-tpl :table-data="tableData" @click="clickItem" />
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { forceUpdateMP3 } from "@/utils/useMP3";
import listTpl from "../common/video-list-tpl.vue";
import Upload from "@/components/common/upload.vue";
import { ElNotification, ElDivider } from "element-plus";
import { fetchMP3List, forceUpdate, IMP3Data } from "@/utils/useRequest";
import { useRouter } from "vue-router";

const router = useRouter();

const showBox = ref(false);
const isLoading = ref(false);
const fileChanged = ref(false);
const tableData = ref([] as IMP3Data[]);

fetchMP3List().then(({ data }) => {
	tableData.value = data;
});

function clickUpload() {
	showBox.value = true;
}

function changeFiles() {
	fileChanged.value = true;
}

function closeUpload() {
	fileChanged.value = false;
	showBox.value = false;
}

function setBoxShow(state: boolean) {
	showBox.value = state;
}

function setBtnLoading(state: boolean) {
	isLoading.value = state;
}

function clickItem(value: { index: number; data: IMP3Data }) {
	const { key } = value.data;
	router.push({
		path: "mp4",
		query: { key },
	});
}

function completeUpload(res: {
	msg: string;
	code: number;
	data: {
		info: string;
	};
}) {
	if (res.data.info.includes("SUCCESS")) {
		setTimeout(() => {
			fetchMP3List().then(({ data }) => {
				tableData.value = data;
			});

			isLoading.value = false;
			forceUpdate(() => {
				showBox.value = false;
				window.location.reload();
			});
		}, 1000);
	} else {
		ElNotification({
			message: `更新失败`,
			type: "error",
		});

		setTimeout(() => {
			if (res.data.info.includes("EXIST")) {
				ElNotification({
					message: `该文件已存在于数据库中`,
					type: "error",
				});
			} else {
				ElNotification({
					message: `错误信息：${res.data.info}`,
					type: "error",
				});
			}
		}, 1500);
	}
}
</script>

<style lang="less">
.table-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
}
</style>
